package com.abss.vote.util;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

/**
 * 资源路径配置
 */
public  class OSSUtils {

    //如果从oss读取文件需要用到的
    public static String endpoint = "oss-cn-qingdao.aliyuncs.com";
    public static String accessKeyId = "LTAIjMPtOLpeU6up";
    public static String accessKeySecret = "CrP5X0XjKX1pdEtuUDXpwgjOmx7nYv";
    public static String bucketName = "mamidiantai-data";

    //oss调用地址
    static String ossurl = "https://oss.mamidiantai.com/";

    public static String uploadFile(byte[] data,String name) {
        OSS ossClient=null;
        try {
            // 创建OSSClient实例。
            ossClient= new OSSClientBuilder().build(OSSUtils.endpoint, OSSUtils.accessKeyId, OSSUtils.accessKeySecret);
            // 上传文件流。
            InputStream inputStream = new ByteArrayInputStream(data);


            //第一个参数，bucket名称
            //第二个参数，上传到oss文件路径和文件名称
            //第三个参数，上传文件输入流
            ossClient.putObject(OSSUtils.bucketName, name, inputStream);

            return OSSUtils.ossurl + name;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭OSSClient。
            if(ossClient!=null)
                ossClient.shutdown();
        }
        return null;
    }

    public static String uploadStream(InputStream stream,String name) {//InputStream stream 文件上传流
        OSS ossClient=null;
        try {
            // 创建OSSClient实例。
            ossClient= new OSSClientBuilder().build(OSSUtils.endpoint, OSSUtils.accessKeyId, OSSUtils.accessKeySecret);

            ossClient.putObject(OSSUtils.bucketName, name, stream);

            return OSSUtils.ossurl + name;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            // 关闭OSSClient。
            if(ossClient!=null)
                ossClient.shutdown();
        }
        return null;
    }
}
